﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.IO;
using CodeCarvings.Piczard.Web;
using CodeCarvings.Piczard;
using System.Xml.Linq;
using CodeCarvings.Piczard.Filters.Watermarks;

namespace Framework.WebmasterTool.GalleryImages
{
    public partial class GalleryImages : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public int cateAlbum;
        public int cateParent;
        public int cateTop;

        protected void Page_Load(object sender, EventArgs e)
        {
            siuUploadImage.ImageRemove += new EventHandler(siuUploadImage_ImageRemove);
            siuUploadImage.ImageUpload += new SimpleImageUpload.ImageUploadEventHandler(siuUploadImage_ImageUpload);
            LoadCateAlbum();
            if (!IsPostBack)
            {
                CheckPermission();
                //CleanImageUploadTemp();
                CallImageUpload();
                LoadCateDDL();
                LoadAlbumByCateAlbum();
                LoadImageAlbumByCateAlbum();
                LoadImageDetails();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.GalleryImage.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        void siuUploadImage_ImageRemove(object sender, EventArgs e)
        {
            chkWatermarkImage.Enabled = true;
        }

        void siuUploadImage_ImageUpload(object sender, SimpleImageUpload.ImageUploadEventArgs args)
        {
            chkWatermarkImage.Enabled = false;
        }

        public void CleanImageUploadTemp()
        {
            foreach (var file in Directory.GetFiles(Server.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
            {
                File.Delete(file);
            }
        }

        public void ImageUpload(SimpleImageUpload ctrImageUpload)
        {
            ctrImageUpload.ImageBackColorApplyMode = PictureTrimmerImageBackColorApplyMode.DoNotApply;
            ctrImageUpload.CropConstraint = new FreeCropConstraint();
            ctrImageUpload.PreviewFilter = new FixedResizeConstraint(200, 200, System.Drawing.Color.Black);
            ctrImageUpload.Text_BrowseButton = "Upload ảnh";
            ctrImageUpload.Text_CancelUploadButton = "Huỷ";
            ctrImageUpload.Text_EditButton = "Sửa ảnh";
            ctrImageUpload.Text_RemoveButton = "Xoá ảnh";
        }

        public void CallImageUpload()
        {
            ImageUpload(siuUploadImage);
        }

        public void LoadSubCateDDL(ref List<udv_CateGalleryImage> allCate, int cateParentID, ref string spaces, string levels)
        {
            List<udv_CateGalleryImage> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
            foreach (var item in subCateBanner)
            {
                ddlCategories.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
                if (entity.udv_CateGalleryImage.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
                {
                    spaces += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
                }
            }
            if (spaces.Length > 6)
                spaces = spaces.Substring(0, spaces.Length - 36);
        }

        public void LoadCateDDL()
        {
            string levels = "|---";
            string spaces = "&nbsp;";
            List<udv_CateGalleryImage> allCate = entity.udv_CateGalleryImage.ToList();
            List<udv_CateGalleryImage> cateBannerParent = allCate.Where(ca => ca.ParentID == 0).ToList();
            foreach (var item in cateBannerParent)
            {
                ddlCategories.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
                LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
            }
        }

        protected void chkWatermarkImage_CheckedChanged(object sender, EventArgs e)
        {
            if (chkWatermarkImage.Checked == true && siuUploadImage.HasImage == false)
            {
                XDocument xDocWatermark = XDocument.Load(Server.MapPath(ConfigPaths.Path_Watermark_Xml));
                XElement xEImage = xDocWatermark.Descendants("img").FirstOrDefault();
                siuUploadImage.PostProcessingFilter = new ImageWatermark(Server.MapPath(ConfigPaths.Path_ImageUpload_Folder_MapPath + xEImage.Value), System.Drawing.ContentAlignment.BottomRight);
            }
            else if (chkWatermarkImage.Checked == false && siuUploadImage.HasImage == false)
            {
                siuUploadImage.PostProcessingFilter = null;
            }
        }

        public void LoadCateAlbum()
        {
            var allAlbum = entity.udv_CateGalleryImage.ToList();
            var parentAlbum = allAlbum.Where(cg => cg.Remove == false).FirstOrDefault();
            cateTop = parentAlbum.CateID;
            if (Request.QueryString["CateID"] != null)
            {
                int cateAlbumID = 0;
                int.TryParse(Request.QueryString["CateID"].ToString(), out cateAlbumID);
                udv_CateGalleryImage cateGalleryImage = allAlbum.Where(cg => cg.CateID == cateAlbumID).FirstOrDefault();
                if (cateGalleryImage != null)
                {
                    ltrTitleFolder.Text = cateGalleryImage.Title;
                    cateAlbum = cateGalleryImage.CateID;
                    if (cateGalleryImage.Remove == false)
                    {
                        cateParent = cateGalleryImage.CateID;
                    }
                    else
                    {
                        cateParent = cateGalleryImage.ParentID.Value;
                    }
                }
                else
                {
                    Response.Redirect("GalleryImages.aspx");
                }
            }
            else
            {
                ltrTitleFolder.Text = parentAlbum.Title;
                cateAlbum = parentAlbum.CateID;
                cateParent = parentAlbum.CateID;
            }
        }

        public void LoadAlbumByCateAlbum()
        {
            var albumByCateAlbum = entity.udv_CateGalleryImage.Where(cg => cg.ParentID == cateAlbum).ToList();
            rpCateGalleryImage.DataSource = albumByCateAlbum;
            rpCateGalleryImage.DataBind();
        }

        public void LoadImageAlbumByCateAlbum()
        {
            var imageAlbumByCateAlbum = entity.udv_GalleryImage.Where(ig => ig.udv_CateGalleryImage.CateID == cateAlbum).OrderByDescending(ig => ig.AddedDate).ToList();
            rpImages.DataSource = imageAlbumByCateAlbum;
            rpImages.DataBind();
        }

        public void LoadImageDetails()
        {
            if (Request.QueryString["CateID"] == null && Request.QueryString["ImageID"] != null)
            {
                int imageID = 0;
                int.TryParse(Request.QueryString["ImageID"].ToString(), out imageID);
                var imageDetails = entity.udv_GalleryImage.Where(gi => gi.ImageID == imageID).FirstOrDefault();
                if (imageDetails != null)
                {
                    imageDetails.udv_CateGalleryImageReference.Load();
                    Response.Redirect("GalleryImages.aspx?CateID=" + imageDetails.udv_CateGalleryImage.CateID + "&ImageID=" + imageDetails.ImageID);
                }
                else
                {
                    Response.Redirect("GalleryImages.aspx");
                }
            }
            else if (Request.QueryString["CateID"] != null && Request.QueryString["ImageID"] != null)
            {
                btnNew.Visible = true;
                int imageID = 0;
                int.TryParse(Request.QueryString["ImageID"].ToString(), out imageID);
                var imageDetails = entity.udv_GalleryImage.Where(gi => gi.ImageID == imageID).FirstOrDefault();
                if (imageDetails != null)
                {
                    imageDetails.udv_CateGalleryImageReference.Load();
                    ddlCategories.SelectedValue = imageDetails.udv_CateGalleryImage.CateID.ToString();
                    if (imageDetails.ImageUrl != null && imageDetails.ImageUrl.Trim() != "")
                    {
                        string sourceImageFilePath = ConfigPaths.Path_GalleryImage_Folder_MapPath + imageDetails.ImageUrl;
                        siuUploadImage.LoadImageFromFileSystem(Server.MapPath(sourceImageFilePath));
                        chkWatermarkImage.Enabled = false;
                    }
                    txtAltImage.Text = imageDetails.ImageAlt.Trim();
                    txtTitle.Text = imageDetails.Title.Trim();
                    txtTitle_en.Text = imageDetails.Title_en.Trim();
                    txtDesciption.Text = imageDetails.Description;
                    txtDesciption_en.Text = imageDetails.Description_en;
                    lblAddedDate.Text = String.Format("{0:dd/MM/yyyy}", imageDetails.AddedDate);
                    lblAddedBy.Text = imageDetails.AddedBy;
                    lblUpdatedDate.Text = String.Format("{0:dd/MM/yyyy}", imageDetails.UpdatedDate);
                    lblUpdatedBy.Text = imageDetails.UpdatedBy;
                    chkIsActive.Checked = imageDetails.IsActive.Value;
                    chkIsTop.Checked = imageDetails.IsTop.Value;
                    txtDisplayOrder.Text = imageDetails.DisplayOrder.ToString();
                }
                else
                {
                    Response.Redirect("GalleryImages.aspx");
                }
            }
        }

        public void ClearForm()
        {
            txtTitle.Text = txtTitle_en.Text = txtAltImage.Text = txtDesciption.Text = txtDesciption_en.Text = lblMessage.Text = "";
            siuUploadImage.UnloadImage();
            btnNew.Visible = false;
            //CleanImageUploadTemp();
        }

        protected void lkbDeleteImage_Click(object sender, EventArgs e)
        {
            int ImageID = int.Parse((sender as LinkButton).CommandArgument);
            var imageGalleryDelete = entity.udv_GalleryImage.Where(gi => gi.ImageID == ImageID).FirstOrDefault();
            if (imageGalleryDelete != null)
            {
                //create db log
                CreateDBLog(null, null, TypeAction.Delete, "Xoá thư viện ảnh: " + imageGalleryDelete.Title, imageGalleryDelete.Description, "", "", "",
                    imageGalleryDelete.IsActive.Value.ToString(), imageGalleryDelete.IsTop.Value.ToString(), "", "");

                Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_GalleryImage_Folder_MapPath + imageGalleryDelete.ImageUrl));
                entity.DeleteObject(imageGalleryDelete);
                entity.SaveChanges();
                //data cache
                Cache.Remove("GalleryImage");
                ////clear outputcache
                //HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                //HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                //HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
                //HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                //HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
                //HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
            }
            LoadAlbumByCateAlbum();
            LoadImageAlbumByCateAlbum();
            ClearForm();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (siuUploadImage.HasImage == false)
            {
                lblMessage.Text = "Chưa upload hình ảnh";
                return;
            }
            if (Request.QueryString["ImageID"] != null)
            {
                int imageID = 0;
                int.TryParse(Request.QueryString["ImageID"].ToString(), out imageID);
                var imageGallery = entity.udv_GalleryImage.Where(gi => gi.ImageID == imageID).FirstOrDefault();
                if (imageGallery != null)
                {
                    int cateGalleryImageID = int.Parse(ddlCategories.SelectedValue);
                    imageGallery.udv_CateGalleryImage = entity.udv_CateGalleryImage.Where(cg => cg.CateID == cateGalleryImageID).FirstOrDefault();
                    if (siuUploadImage.HasNewImage == true)
                    {
                        Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_GalleryImage_Folder_MapPath + imageGallery.ImageUrl.Trim()));
                        string fileNameImage = Globals.GetFileName(siuUploadImage.SourceImageClientFileName);
                        siuUploadImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_GalleryImage_Folder + fileNameImage);
                        imageGallery.ImageUrl = fileNameImage;
                    }
                    imageGallery.ImageAlt = txtAltImage.Text.Trim();
                    string oldTitle = imageGallery.Title;
                    imageGallery.Title = txtTitle.Text.Trim();
                    imageGallery.Title_en = txtTitle_en.Text.Trim();
                    imageGallery.Description = txtDesciption.Text.Trim();
                    imageGallery.Description_en = txtDesciption_en.Text.Trim();
                    imageGallery.UpdatedDate = DateTime.Now;
                    imageGallery.UpdatedBy = Membership.GetUser().UserName;
                    imageGallery.IsActive = chkIsActive.Checked;
                    imageGallery.IsTop = chkIsTop.Checked;
                    imageGallery.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                    entity.SaveChanges();
                    LoadAlbumByCateAlbum();
                    LoadImageAlbumByCateAlbum();
                    ClearForm();

                    //create db log
                    CreateDBLog(null, null, TypeAction.Update, "Cập nhật thư viện ảnh: " + oldTitle + " - " + imageGallery.Title, imageGallery.Description, "", "", "",
                            imageGallery.IsActive.Value.ToString(), imageGallery.IsTop.Value.ToString(), "", "");

                    //data cache
                    Cache.Remove("GalleryImage");
                    ////clear outputcache
                    //HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
                }
                else
                {
                    Response.Redirect("GalleryImages.aspx");
                }
            }
            else
            {
                udv_GalleryImage imageGallery = new udv_GalleryImage();
                int cateGalleryImageID = int.Parse(ddlCategories.SelectedValue);
                imageGallery.udv_CateGalleryImage = entity.udv_CateGalleryImage.Where(cg => cg.CateID == cateGalleryImageID).FirstOrDefault();
                if (siuUploadImage.HasImage == true)
                {
                    string fileNameImage = Globals.GetFileName(siuUploadImage.SourceImageClientFileName);
                    siuUploadImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_GalleryImage_Folder + fileNameImage);
                    imageGallery.ImageUrl = fileNameImage;
                }
                imageGallery.ImageAlt = txtAltImage.Text.Trim();
                imageGallery.Title = txtTitle.Text.Trim();
                imageGallery.Title_en = txtTitle_en.Text.Trim();
                imageGallery.Description = txtDesciption.Text.Trim();
                imageGallery.Description_en = txtDesciption_en.Text.Trim();
                imageGallery.AddedDate = DateTime.Now;
                imageGallery.AddedBy = Membership.GetUser().UserName;
                imageGallery.UpdatedDate = DateTime.Now;
                imageGallery.UpdatedBy = Membership.GetUser().UserName;
                imageGallery.IsActive = chkIsActive.Checked;
                imageGallery.IsTop = chkIsTop.Checked;
                imageGallery.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                entity.AddToudv_GalleryImage(imageGallery);
                entity.SaveChanges();
                LoadAlbumByCateAlbum();
                LoadImageAlbumByCateAlbum();
                ClearForm();

                //create db log
                CreateDBLog(null, null, TypeAction.Insert, "Tạo thư viện ảnh: " + imageGallery.Title, imageGallery.Description, "", "", "",
                        imageGallery.IsActive.Value.ToString(), imageGallery.IsTop.Value.ToString(), "", "");

                //clear outputcache
                HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
                HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
                HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            string urlRedirect = Request.Url.AbsoluteUri.ToLower();
            if (urlRedirect.Contains("imageid"))
            {
                urlRedirect = urlRedirect.Substring(0, urlRedirect.IndexOf("imageid") - 1);
            }
            Response.Redirect(urlRedirect);
        }

        protected void btnCateGalleryImage_Click(object sender, EventArgs e)
        {
            Response.Redirect("Categories.aspx");
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}